package cn.yuanqiao.common.filter;

import cn.yuanqiao.common.constant.HttpStatus;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.license.YanzhengService;
import cn.yuanqiao.common.utils.ServletUtils;
import cn.yuanqiao.common.utils.StringUtils;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 系统授权
 */
@Component
public class LicenseFilter implements Filter, Ordered {
    protected final Logger log = LoggerFactory.getLogger(LicenseFilter.class);

    @Value("${YQDA_LICENSE}")
    private String licenseFile;
    //今天验证成功不再验证
    private Boolean isLicense = false;
    //每天24点以后验证一次登录接口
    private LocalDateTime licenseData = LocalDateTime.now();

    @Override
    public int getOrder() {
        return -300;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request,response);
        /*if(!isLicense || needLicense()){
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            String url = httpRequest.getRequestURI();
            //只拦截登录接口
            if(url.endsWith("/login")){
                log.info("开始验证授权={}",licenseFile);
                java.io.File licFile = new java.io.File(licenseFile);
                if(licFile.exists()){
                    java.util.Map<String,String> lic = YanzhengService.getYanzhengma(licFile);
                    if("1".equals(lic.get("code"))){
                        log.info("授权验证成功={}",lic.get("msg"));
                        isLicense = true;
                        licenseData = LocalDateTime.now();
                        chain.doFilter(request,response);
                    }else {
                        log.error("授权验证失败={}", lic.get("msg"));
                        ServletUtils.renderString(httpResponse, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED_LICENSE, "系统未授权")));
                    }
                }else {
                    log.error("授权文件不存在={}", licenseFile);
                    ServletUtils.renderString(httpResponse, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED_LICENSE, "系统未授权")));
                }
            }else {
                chain.doFilter(request,response);
            }
        }else {
            chain.doFilter(request,response);
        }*/
    }

    @Override
    public void destroy() {

    }

    private Boolean needLicense(){
        // 假设这是你要检查的时间
        LocalDateTime specificTime = licenseData;

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 提取日期的部分进行比较
        LocalDate specificDate = specificTime.toLocalDate();
        LocalDate currentDate = now.toLocalDate();

        // 如果specificTime的日期小于当前日期，说明已经过了24点
        //if (specificDate.isBefore(currentDate) || specificDate.isEqual(currentDate)) {
        // 注意：这里也包括了等于当前日期的情况，因为即使等于当前日期，
        // 也可能已经过了specificTime指定的时间（例如现在是2023-10-01 00:01，而specificTime是2023-10-01 23:59）
        // 如果你只想检查是否过了午夜（即是否到了第二天），则应该只使用isBefore
        //System.out.println("已经过了24点（或已经是第二天）。");
        //} else {
        //System.out.println("还没有过24点。");
        //}

        // 如果你只想检查是否过了午夜（即是否到了第二天），可以这样做：
        if (!specificDate.equals(currentDate)) {
            //System.out.println("已经过了午夜，到了第二天。");
            //log.info("需要验证授权");
            isLicense = false;
            return true;
        } else {
            //System.out.println("还没有过午夜。");
            //log.info("无需验证授权");
            return false;
        }
    }
}
